#include <bits/stdc++.h>

#include <atcoder/all>
#define LL long long
using namespace std;
using namespace atcoder;

struct SpareTable {
  int len;
  vector<int> to_dep;
  vector<vector<int>> st;
  vector<int> num;

  SpareTable(const vector<int>& number) {
    num = number;
    len = num.size();
    to_dep.resize(len + 1, 0);
    for (int i = 2; i <= len; i++) {
      to_dep[i] = to_dep[i >> 1] + 1;
    }
    int depth = to_dep.back();
    st.resize(depth + 1, vector<int>(len));

    for (int i = 0; i < len; i++) {
      st[0][i] = i;
    }
    for (int d = 0; d < depth; d++) {
      for (int i = 0; i + (2 << d) <= len; i++)
        if (num[st[d][i]] > num[st[d][i + (1 << d)]]) {
          st[d + 1][i] = st[d][i];
        } else {
          st[d + 1][i] = st[d][i + (1 << d)];
        }
    }
  }

  int GetMaxID(int l, int r) const {
    int d = to_dep[r - l + 1];
    int left = st[d][l], right = st[d][r - (1 << d) + 1];

    return num[left] > num[right] ? left : right;
  }
};

LL DFS(int now, int l, int r, const SpareTable& st) {
  // cout << now << " " << l << " " << r << "\n";
  LL ret = 0;

  if (l < now) {
    int lc = st.GetMaxID(l, now - 1);

    ret = max(ret, DFS(lc, l, now - 1, st) + abs(now - lc));
  }
  if (now < r) {
    int rc = st.GetMaxID(now + 1, r);

    ret = max(ret, DFS(rc, now + 1, r, st) + abs(now - rc));
  }
  return ret;
}

int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  int N, root;

  cin >> N;
  vector<int> P(N);
  for (int i = 0; i < N; i++) {
    cin >> P[i];
    if (P[i] == N) {
      root = i;
    }
  }
  SpareTable st(P);
  cout << DFS(root, 0, N - 1, st) << "\n";
  return 0;
}
